<template>
  <el-dialog v-el-drag-dialog title="楼层费设置" :visible.sync="visible" width="1136px" @closed="reset">
    <div class="top">
      <el-descriptions size="medium" border>
        <el-descriptions-item label="编码">{{ temp.goodsCode }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ temp.goodsName }}</el-descriptions-item>
        <el-descriptions-item label="类别">{{ temp.gtName }}</el-descriptions-item>
      </el-descriptions>
      <div class="btn">
        <el-button type="primary" @click="addRow">新增</el-button>
      </div>
    </div>

    <lb-table class="table" :column="tableData.column" :data="tableData.data" />

    <span slot="footer" class="dialog-footer">
      <el-button @click="reset">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { keepDotLength } from '@/utils/math'
  import { queryFloorCostData, floorfeeSave, floorfeeDelete } from '@/api'
  export default {
    name: 'distributionDialog',
    data() {
      return {
        visible: false,
        org: null,
        temp: {},
        tempdata: {
          spFee0: '0'
        },
        tableData: {
          column: [
            { type: 'index' },
            {
              prop: 'floorStart',
              width: 100,
              label: '起始楼层',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={1}
                      max={99}
                      precision={0}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'floorEnd',
              width: 100,
              label: '封顶楼层',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={1}
                      max={99}
                      precision={0}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'baseFee',
              label: '基准值(元)',
              width: 120,
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={0}
                      max={999999999}
                      precision={2}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'floorFee1',
              width: 98,
              label: '居民(元)',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={0}
                      max={999999999}
                      precision={2}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'floorFee2',
              width: 98,
              label: '商业(元)',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={0}
                      max={999999999}
                      precision={2}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'floorFee4',
              width: 98,
              label: '工业(元)',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={0}
                      max={999999999}
                      precision={2}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'mode',
              width: 120,
              label: '模式',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-select v-model={scope.row[scope.column.property]} filterable placeholder='请选择'>
                       <el-option key={1} label='逐层递增' value={1}></el-option>
                       <el-option key={2} label='逐层递减' value={2}></el-option>
                       <el-option key={3} label='固定' value={3}></el-option>
                    </el-select>
                  ) : (
                    <span>{
                      (function() {
                        if (scope.row[scope.column.property] === 1) {
                          return '逐层递增'
                        }
                        if (scope.row[scope.column.property] === 2) {
                          return '逐层递减'
                        }
                        if (scope.row[scope.column.property] === 3) {
                          return '固定'
                        }
                      }())
                    }</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'modeAmount',
              width: 120,
              label: '模式金额(元)',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={0}
                      max={999}
                      precision={2}
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                      disabled={scope.row.mode === 3}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property] && scope.row[scope.column.property] !== 0 ? Number(scope.row[scope.column.property]).toFixed(2) : ''}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              width: 80,
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-link underline={false} onClick={() => { this.handleSave(scope) }}>保存</el-link>
                      <el-link underline={false} onClick={() => { this.handleCancle(scope) }}>取消</el-link>
                    </div>
                  ) : (
                    <div>
                      <el-link underline={false} onClick={() => { this.handleEdit(scope) }}>编辑</el-link>
                      <el-link underline={false} type='danger' onClick={() => { this.handleDel(scope) }}>删除</el-link>
                    </div>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        },
        realData: []
      }
    },
    mounted() {},
    methods: {
      open(temp, org) {
        this.org = org
        this.getDeaultData(temp, org)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
          }
        })
      },
      async getDeaultData(temp, org) {
        const res = await queryFloorCostData({
          goodsId: temp.goodsId,
          orgId: org.orgId
        })
        if (res.data && res.data.length > 0) {
          this.tableData.data = this.tableData.data.concat(res.data)
          this.tableData.defaultData = JSON.parse(JSON.stringify(this.tableData.data))
          this.realData = res.data
        }
      },
      async setDeaultData(row) {
        const res = await queryFloorCostData({
          goodsId: this.temp.goodsId,
          orgId: this.org.orgId
        })
        if (res.data && res.data.length > 0) {
          this.realData = res.data
          const index = res.data.findIndex(item => item.floorStart === row.floorStart && item.floorEnd === row.floorEnd)
          const match = res.data.find(item => item.floorStart === row.floorStart && item.floorEnd === row.floorEnd)
          this.tableData.data.splice(index, 1, {
            ...row,
            ...match
          })
        }
      },
      inputFormat(e) {
        e.target.value = keepDotLength(e.target.value)
      },
      addRow() {
        if (this.tableData.data.some(item => item._edit)) {
          this.$message.error('请先保存编辑行')
          return
        }
        const data = this.tableData.data
        data.push({
          _edit: true,
          mode: 1
        })
      },
      async handleSave(scope) {
        const row = scope.row
        const json = { ...row }
        if (!json.floorStart) {
          this.$message.error('请输入起始楼层')
          return
        }
        if (!json.floorEnd) {
          this.$message.error('请输入封顶楼层')
          return
        }
        if (json.floorEnd && Number(json.floorEnd) < Number(json.floorStart)) {
          this.$message.error('封顶楼层不能小于起始楼层')
          return
        }
        if (!json.baseFee && json.baseFee !== 0) {
          this.$message.error('请输入基准值或指定客户类型')
          return
        }
        if (json.mode !== 3 && !json.modeAmount) {
          this.$message.error('请选择模式金额')
          return
        }
        const res = await queryFloorCostData({
          goodsId: this.temp.goodsId,
          orgId: this.org.orgId
        })
        const copy = JSON.parse(JSON.stringify(res.data))
        for (const i in copy) {
          const item = copy[i]
          if (scope.$index === Number(i)) {
            continue
          }
          if (((scope.row.floorStart <= item.floorStart && scope.row.floorEnd >= item.floorStart) || (scope.row.floorStart <= item.floorEnd && scope.row.floorEnd >= item.floorEnd) || (scope.row.floorStart >= item.floorStart && scope.row.floorEnd <= item.floorEnd)) &&
            ((item.baseFee && scope.row.baseFee) || (item.floorFee1 && scope.row.floorFee1) || (item.floorFee2 && scope.row.floorFee2) || (item.floorFee4 && scope.row.floorFee4))) {
            this.$message.error('不允许重复设置同一楼层费')
            return
          }
        }
        json.goodsName = this.temp.goodsName
        json.gtId = this.temp.gTypeId
        json.gtName = this.temp.gtName
        json.orgId = this.org.orgId
        json.orgName = this.org.orgName
        json.orgSNNo = this.org.orgSNNo
        json.goodsId = this.temp.goodsId
        this.$set(row, '_edit', false)
        await floorfeeSave(json)
        this.resolve()
        // this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.setDeaultData(scope.row)
      },
      handleDel(scope) {
        const id = scope.row.id
        if (id) {
          floorfeeDelete({ id }).then(res => {
            if (res.success) {
              this.tableData.data.splice(scope.$index, 1)
              this.tableData.defaultData.splice(scope.$index, 1)
              this.$emit('fetch')
              this.$message({
                message: '操作成功！',
                type: 'success'
              })
            } else {
              this.$message({
                message: '操作失败！',
                type: 'error'
              })
            }
          })
        } else {
          const row = this.tableData.data
          this.$delete(row, scope.$index)
        }
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleCancle(scope) {
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableData.data,
          scope.$index,
          JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index]))
        )
      },
      reset() {
        this.visible = false
        this.$emit('fetch')
        this.tableData.data = []
        this.tableData.defaultData = []
      }
    }
  }
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .el-descriptions {
    flex: 1;
  }
  .btn {
    width: 50px;
    margin-left: 10px;
  }
}
.table {
  /deep/ .el-input-number.is-without-controls .el-input__inner {
    width: 80px;
    padding-right: 5px;
    padding-left: 5px;
  }
}
</style>
